package com.sskj.gocoin.v.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.R2;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.ClassicsHeader;
import com.sskj.gocoin.common.MarketWebSocket;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.common.decoration.DividerLineItemDecoration;
import com.sskj.gocoin.m.bean.LevelBean;
import com.sskj.gocoin.m.bean.TradePositionListBean;
import com.sskj.gocoin.p.fragment.NewTradePositionFragmentPst;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.EditChangeUtil;
import com.sskj.gocoin.utils.NumberUtil;
import com.sskj.gocoin.utils.TipUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.activity.TradeActivity;
import com.sskj.gocoin.v.base.BaseViewPagerFragment;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * <pre>
 *     author : 吕志豪
 *     e-mail : 1030753080@qq.com
 *     time   : 2018/04/09
 *     desc   :杠杆交易 -->持仓订单
 *     version: 1.0
 * </pre>
 */

public class NewTradePositionFragment extends BaseViewPagerFragment<TradeActivity, NewTradePositionFragmentPst> {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private MarketWebSocket mWebSocket;
    public String code = "";

    private DateFormat dateFormat = new SimpleDateFormat("HH:mm MM/dd");

    private BaseAdapter<TradePositionListBean> adapter;
    private MaterialDialog mDialog;
    /**
     * 最小止盈点位
     */
    private int mLowWinPoint;
    /**
     * 最小止损点位
     */
    private int mLowLossPoint;
    /**
     * 当前修改止盈止损的订单ID
     */
    private String mHoldId;

    /**
     * 当前修改止盈止损币种的最小浮动价格
     */
    private double mVarPrice;
    private TextView mDialogStopwinHint;
    private TextView mDialogStoplossHint;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_trade_position;
    }

    @Override
    public NewTradePositionFragmentPst getPresenter() {
        return new NewTradePositionFragmentPst();
    }

    //    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (!hidden) {
//            initWebSocket();
//        } else {
//            if (mWebSocket != null) {
//                mWebSocket.closeWebSocket();
//            }
//        }
//    }


//    @Override
//    public void onPause() {
//        super.onPause();
//        if (mWebSocket != null) {
//            mWebSocket.closeWebSocket();
//        }
//    }

    @Override
    public void initView() {
        ClassicsHeader classicsHeader = new ClassicsHeader(getActivity());
        classicsHeader.setBackgroundColor(getResources().getColor(R.color.background));
        refreshLayout.setRefreshHeader(classicsHeader);
        refreshLayout.setOnRefreshListener(refreshLayout1 -> {
            refreshLayout.finishRefresh();
            mPresenter.loadData(code);
        });
        // 获取上一个Fragment过来的code值
        code = getArguments().getString("code");
        Log.i("msg001", "code:" + code);
    }

    public void stopRefresh() {

    }

    @Override
    public void initData() {
        mPresenter.loadData(code);
    }


//    public void initWebSocket() {
//        String text = "{\"type\":\"vb_okex\"}";
//        mWebSocket = new MarketWebSocket(HttpConfig.BTC_WS, "NewTradePositionFragment", text);
//        mWebSocket.setListener(message -> mPresenter.loadData());
//    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity()).setFirstDraw(false));
        adapter = new BaseAdapter<TradePositionListBean>(R.layout.recy_item_trade_position_h, new ArrayList<>(), recyclerView) {
            @Override
            public void bind(ViewHolder holder, TradePositionListBean data) {
                holder.setText(R.id.tv_bz, data.getPname())
                        .setText(R.id.tv_lx, data.getOtype() == 1 ? App.INSTANCE.getString(R.string.strNewTradePositionFragment209) : App.INSTANCE.getString(R.string.strNewTradePositionFragment210))
                        .setTextColor(R.id.tv_lx, getResources().getColor(data.getOtype() == 1 ? R.color.market_up : R.color.market_down))
                        .setText(R.id.tv_cjj, App.INSTANCE.getString(R.string.xmlrecy_item_trade_position_h50) + "  " + data.getBuyprice())  // 持仓价
                        .setText(R.id.tv_ccl, App.INSTANCE.getString(R.string.xmlrecy_item_trade_position_h63) + "  " + data.getBuynum())  // 持仓量
                        .setText(R.id.tv_je, App.INSTANCE.getString(R.string.trade_sec) + "  " + data.getTotalprice())  // 保证金
                        .setText(R.id.tv_xj, App.INSTANCE.getString(R.string.xmlrecy_item_trade_position_h93) + "  " + data.getNewprice())  // 限价
                        .setText(R.id.tv_fdyk, App.INSTANCE.getString(R.string.xmlrecy_item_trade_position_h169) + "  " + data.getFdyk())  // 浮动盈亏
                        .setText(R.id.tv_sxf, App.INSTANCE.getString(R.string.xmlrecy_item_trade_position_h110) + "  " + data.getSxfee())  // 手续费
                        .setText(R.id.tv_dayfee, App.INSTANCE.getString(R.string.xmlrecy_item_trade_position_h122) + "  " + data.getDayfee())  // 利息
                        .setText(R.id.tv_stopwin, App.INSTANCE.getString(R.string.xmllayout_head_view217) + "  " + data.getPoit_win())  // 止盈
                        .setText(R.id.tv_stoploss, App.INSTANCE.getString(R.string.xmllayout_head_view236) + "  " + data.getPoit_loss())  // 止损
                        .setText(R.id.tv_time, dateFormat.format(data.getAddtime() * 1000))
                        .setText(R.id.leverage, App.INSTANCE.getString(R.string.leverage) + "  " + data.getLeverage());
                ClickUtil.click(holder.getView(R.id.trade_sale), () -> {
                    TipUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.strNewTradePositionFragment211), App.INSTANCE.getString(R.string.strNewTradePositionFragment212), () -> {
                        mPresenter.pingcang(data);
                    }).show();
                });
                // 浮动盈亏设置红色绿色（红涨绿跌）
                if (data.getFdyk().contains("-")) {
                    holder.setTextColor(R.id.tv_fdyk, getResources().getColor(R.color.market_down));  // 浮动盈亏
                } else {
                    holder.setTextColor(R.id.tv_fdyk, getResources().getColor(R.color.market_up));
                }


                if (data.getHold_id().equals(mHoldId)) {
                    double priceDifference;
                    if (data.getOtype() == 1) {
                        priceDifference = Double.valueOf(data.getNewprice()) - Double.valueOf(data.getBuyprice());
                    } else {
                        priceDifference = Double.valueOf(data.getBuyprice()) - Double.valueOf(data.getNewprice());
                    }
                    calculatePoint(data.getOtype(), priceDifference);
                }
                ClickUtil.click(holder.getView(R.id.trade_edit), () -> {  // 编辑
                    mHoldId = data.getHold_id();
                    double priceDifference;
                    if (data.getOtype() == 1) {
                        priceDifference = Double.valueOf(data.getNewprice()) - Double.valueOf(data.getBuyprice());
                    } else {
                        priceDifference = Double.valueOf(data.getBuyprice()) - Double.valueOf(data.getNewprice());
                    }
                    mPresenter.getLeveRange(data.getPname().toLowerCase(), data.getOtype(), priceDifference, data.getHold_id(), data.getPoit_win(), data.getPoit_loss());
                });
            }
        };
        adapter.setEmtyView();
        recyclerView.setAdapter(adapter);
    }

    void showEditDialog(double dataStopwin, double dataStoploss, String orderId, String poit_win, String poit_loss) {
        mDialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.dialog_edit_stop, false)
                .autoDismiss(true)
                .show();
        mDialog.setOnDismissListener(v -> {
            mHoldId = null;
        });
        View customeView = mDialog.getCustomView();
        EditText dialogStopwinEdit = customeView.findViewById(R.id.dialog_edit_stopwin);  // 止盈输入框
        EditText dialogStoplossEdit = customeView.findViewById(R.id.dialog_edit_stoploss); // 止损输入框
        mDialogStopwinHint = customeView.findViewById(R.id.dialog_input_stopwin_hint);  // 止盈  区间
        mDialogStoplossHint = customeView.findViewById(R.id.dialog_input_stoploss_hint);  // 止损 区间

        if (NumberUtil.isNumeric(poit_win)){
            if (Double.parseDouble(poit_win)==0){
                dialogStopwinEdit.setText("");
            }else {
                dialogStopwinEdit.setText(poit_win);
            }
        }
        if (NumberUtil.isNumeric(poit_loss)){
            if (Double.parseDouble(poit_win)==0){
                dialogStoplossEdit.setText("");
            }else {
                dialogStoplossEdit.setText(poit_loss);
            }
        }

//        mDialogStopwinHint.setText(">=" + mLowWinPoint);
//        mDialogStoplossHint.setText(">=" + mLowLossPoint);
        mDialogStopwinHint.setText("");
        mDialogStoplossHint.setText("");
        //止损  +
        customeView.findViewById(R.id.dialog_stoploss_increase).setOnClickListener(v -> {
            String trim = dialogStoplossEdit.getText().toString().trim();
            Double doubleTrim = Double.valueOf(TextUtils.isEmpty(trim) ? "0" : trim);
//            if (integer < dataStoploss) {
//                integer++;
//            }
            doubleTrim++;
            dialogStoplossEdit.setText(String.valueOf(doubleTrim));
        });
        //止损  -
        customeView.findViewById(R.id.dialog_stoploss_decrease).setOnClickListener(v -> {
            String trim = dialogStoplossEdit.getText().toString().trim();
            Double doubleTrim = Double.valueOf(TextUtils.isEmpty(trim) ? "0" : trim);
//            if (integer > mLowLossPoint) {
//                integer--;
//            }
            if (doubleTrim > 1) {
                doubleTrim--;
            }
            dialogStoplossEdit.setText(String.valueOf(doubleTrim));
        });
        //止盈  +
        customeView.findViewById(R.id.dialog_stopwin_increase).setOnClickListener(v -> {
            String trim = dialogStopwinEdit.getText().toString().trim();
            Double doubleTrim = Double.valueOf(TextUtils.isEmpty(trim) ? "0" : trim);
//            if (integer < dataStopwin) {
//                integer++;
//            }
            doubleTrim++;
            dialogStopwinEdit.setText(String.valueOf(doubleTrim));
        });
        //止盈  -
        customeView.findViewById(R.id.dialog_stopwin_decrease).setOnClickListener(v -> {
            String trim = dialogStopwinEdit.getText().toString().trim();
            Double doubleTrim = Double.valueOf(TextUtils.isEmpty(trim) ? "0" : trim);
//            if (integer > mLowWinPoint) {
//                integer--;
//            }
            if (doubleTrim > 1) {
                doubleTrim--;
            }
            dialogStopwinEdit.setText(String.valueOf(doubleTrim));
        });
        customeView.findViewById(R.id.dialog_cancel).setOnClickListener(v -> {
            mDialog.dismiss();
        });

        //止盈价格
        EditChangeUtil.onChange(dialogStopwinEdit, s -> {
            if (!TextUtils.isEmpty(s.toString())) {
                Double aDouble = Double.valueOf(s.toString());
                if (s.toString().contains(".")) {
                    int pointLength = s.toString().length() - (s.toString().indexOf(".")) - 1;  //获取小数点有几位数字
                    if (pointLength > 4) {
                        dialogStopwinEdit.setText(NumberUtil.keep4(s.toString()));
                        dialogStopwinEdit.setSelection(dialogStopwinEdit.getText().toString().trim().length());
                    }
                }
            }
        });
        //止损价格
        EditChangeUtil.onChange(dialogStoplossEdit, s -> {
            if (!TextUtils.isEmpty(s.toString())) {
                Double aDouble = Double.valueOf(s.toString());
                if (s.toString().contains(".")) {
                    int pointLength = s.toString().length() - (s.toString().indexOf(".")) - 1;  //获取小数点有几位数字
                    if (pointLength > 4) {
                        dialogStoplossEdit.setText(NumberUtil.keep4(s.toString()));
                        dialogStoplossEdit.setSelection(dialogStoplossEdit.getText().toString().trim().length());
                    }
                }
            }
        });

        ClickUtil.click(customeView.findViewById(R.id.dialog_submit), () -> {
            String stopwinValue = dialogStopwinEdit.getText().toString().trim();
            String stoplossValue = dialogStoplossEdit.getText().toString().trim();

            if (TextUtils.isEmpty(stopwinValue)) {
                stopwinValue = "0";
            }
            if (TextUtils.isEmpty(stoplossValue)) {
                stoplossValue = "0";
            }

//            if (Integer.valueOf(stopwinValue) != 0 && Integer.valueOf(stopwinValue) < mLowWinPoint) {
//                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strNewTradePositionFragment222) + mLowWinPoint);
//                return;
//            }
//            if (Integer.valueOf(stoplossValue) != 0 && Integer.valueOf(stoplossValue) < mLowLossPoint) {
//                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strNewTradePositionFragment223) + mLowLossPoint);
//                return;
//            }
            mDialog.dismiss();
            mPresenter.setPoint(orderId, stopwinValue, stoplossValue);
        });
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.loadData(code);
        }
    }

    public void updateData(List<TradePositionListBean> data) {
        adapter.setNewData(data);
    }

    public void onPingChangSuccess(TradePositionListBean data) {
        adapter.getData().remove(data);
        adapter.notifyDataSetChanged();
    }

    /**
     * 全部交易订单界面更新，有定时刷新，所以有数据时再刷新
     */
    public void update() {
        if (!isHidden() && adapter.getItemCount() > 0) {
            mPresenter.loadData(code);
        }
    }

    /**
     * 合约交易界面更新
     */
    @Override
    public void updateData() {
        if (!isHidden() && mPresenter != null) {
            mPresenter.loadData(code);
        }
    }

    @Override
    public void updateData(String code) {
        this.code = code;
        if (!isHidden() && mPresenter != null) {
            mPresenter.loadData(code);
        }
    }

    public void onSetPointSuccess(String msg) {
        ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(msg);
        mPresenter.loadData(code);
    }

    private void calculatePoint(int otype, double priceDifference) {
        int pointValue;
        if (mVarPrice != 0) {
            pointValue = (int) (Math.abs(priceDifference) / mVarPrice + 1);
            mLowWinPoint = 0;
            mLowLossPoint = 0;
            if (otype == 1) {//做多
                if (priceDifference > 0) {
                    mLowWinPoint = pointValue;
                } else {
                    mLowLossPoint = pointValue;
                }
            } else {//做空
                if (priceDifference > 0) {
                    mLowWinPoint = pointValue;
                } else {
                    mLowLossPoint = pointValue;
                }
            }
//            if (mDialogStopwinHint != null) {
//                mDialogStopwinHint.setText(">=" + mLowWinPoint);
//                mDialogStoplossHint.setText(">=" + mLowLossPoint);
//            }

        }
    }

    public void onLeveSuccess(LevelBean levelBean, int otype, double priceDifference, String hold_id, String poit_win, String poit_loss) {
        int pointValue;
        mVarPrice = levelBean.getVar_price();
//        if (otype != 1) {
//            pointValue = (int) (Math.abs(priceDifference) / levelBean.getVar_price() - 1);
//        } else {
//        }
        pointValue = (int) (Math.abs(priceDifference) / levelBean.getVar_price() + 1);
        mLowWinPoint = 0;
        mLowLossPoint = 0;
        if (otype == 1) {//做多
            if (priceDifference > 0) {
                mLowWinPoint = pointValue;
            } else {
                mLowLossPoint = pointValue;
            }
        } else {//做空
            if (priceDifference > 0) {
                mLowWinPoint = pointValue;
            } else {
                mLowLossPoint = pointValue;
            }
        }
        showEditDialog(levelBean.getStopwin(), levelBean.getStoploss(), hold_id, poit_win, poit_loss);
    }
}
